
import { InjectRepository } from '@nestjs/typeorm';
import {Repository, Not, In, Like, DataSource, QueryRunner} from 'typeorm';
import {forwardRef, Inject, Injectable} from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateTeacherDto, UpdateTeacherDto, QueryTeacherDto } from './dto/teacher.dto';
import { TeacherEntity } from './entities/teacher.entity';
import {UserService} from "../../system/user/user.service";
import {UserEntity} from "../../system/user/entities/sys-user.entity";
import {StudentEntity} from "../student/entities/student.entity";

@Injectable()
export class TeacherService {
  constructor(
      @InjectRepository(TeacherEntity)
      private readonly teacherEntityRep: Repository<TeacherEntity>,
      @InjectRepository(UserEntity)
      private readonly userEntityRep: Repository<UserEntity>,
      private dataSource: DataSource,
      @Inject(forwardRef(() => UserService))
      private readonly userService: UserService,
  ) {}
  async create(createTeacherDto: CreateTeacherDto) {

    createTeacherDto.isTeacher = '1'
    createTeacherDto.teacherName = createTeacherDto.nickName

    // https://baijiahao.baidu.com/s?id=1826212692710950384&wfr=spider&for=pc
    const queryRunner = this.dataSource.createQueryRunner()
    await queryRunner.startTransaction()
    try {
      const userId = await this.userService.create(createTeacherDto,true)
      createTeacherDto.teacherId = userId as number;

      // 保存教师信息（使用事务）
      const teacherEntity = queryRunner.manager.create(TeacherEntity, createTeacherDto);
      const res = await queryRunner.manager.save(teacherEntity);

      // 提交事务
      await queryRunner.commitTransaction();

      return ResultData.ok(res);

    } catch (error) {
      // 回滚事务
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      // 释放 QueryRunner 资源
      await queryRunner.release();
    }
  }


  // 数据处理函数
  private  returnFormatDate(data:TeacherEntity[] | TeacherEntity) {
    const getData = (value:TeacherEntity)=>{
      const { user, ...rest } = value;
      return {
        ...rest,
        nickName:user.nickName,
        sex:user.sex,
        avatar:user.avatar,
        deptId:user.deptId,
        email:user.email,
        userName:user.userName,
        phonenumber:user.phonenumber
      }
    }
    if(Array.isArray(data)){
      return  data.map(item=>getData(item))
    }else{
      return getData(data)
    }
  }

  async findAll(query :QueryTeacherDto ) {
    const entity = this.teacherEntityRep.createQueryBuilder('entity');

    entity.leftJoinAndSelect('entity.user', 'user')

    entity.where({ delFlag: '0'});
    if(query.id){
      entity.andWhere("entity.id = :id", {id: query.id});
    }
    if(query.createBy){
      entity.andWhere("entity.createBy = :createBy", {createBy: query.createBy});
    }
    if(query.params?.beginTime && query.params?.endTime){
      entity.andWhere("entity.createTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
    }
    if(query.updateBy){
      entity.andWhere("entity.updateBy = :updateBy", {updateBy: query.updateBy});
    }
    if(query.params?.beginTime && query.params?.endTime){
      entity.andWhere("entity.updateTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
    }
    if(query.remark){
      entity.andWhere("entity.remark = :remark", {remark: query.remark});
    }
    if(query.teacherName){
      entity.andWhere("entity.teacherName LIKE :teacherName", {teacherName: `%${query.teacherName}%`});
    }
    if(query.idCard){
      entity.andWhere("entity.idCard = :idCard", {idCard: query.idCard});
    }
    if(query.teacherNumber){
      entity.andWhere("entity.teacherNumber = :teacherNumber", {teacherNumber: query.teacherNumber});
    }
    if(query.sex){
      entity.andWhere("entity.phone = :sex", {sex: query.sex});
    }
    if(query.state){
      entity.andWhere("entity.state = :state", {state: query.state});
    }
    if(query.teacherId){
      entity.andWhere("entity.teacherId = :teacherId", {teacherId: query.teacherId});
    }
    if(query.schoolId){
      entity.andWhere("entity.schoolId = :schoolId", {schoolId: query.schoolId});
    }
    if(query.teacherLevel){
      entity.andWhere("entity.teacherLevel = :teacherLevel", {teacherLevel: query.teacherLevel});
    }
    if(query.degree){
      entity.andWhere("entity.degree = :degree", {degree: query.degree});
    }
    if(query.experience){
      entity.andWhere("entity.experience = :experience", {experience: query.experience});
    }
    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list:this.returnFormatDate(list),
      total,
    });
  }

  async findOne(id: number) {
    const teacher = await this.teacherEntityRep.findOne({
      where: {
        delFlag: '0',
        id: id,
      },
    });
    const user = await this.userService.findOne(teacher.teacherId)
    const roleIds = user.data.roleIds;
    const postIds = user.data.postIds
    delete user.data.data.password
    const { nickName, phonenumber, email, sex, deptId, userName,userId } = user.data.data;
    return ResultData.ok({
      ...teacher,
      nickName, phonenumber, email, sex, deptId,userName,userId,
      roleIds: roleIds || [],
      postIds: postIds || [],
    });
  }

  async update(updateTeacherDto: UpdateTeacherDto) {
    // 确保传入的 DTO 包含必要的 ID 信息
    if (!updateTeacherDto.id || !updateTeacherDto.userId) {
      throw new Error('缺少必要的参数: id 或 userId');
    }

    // 获取 TeacherEntity 和 UserEntity 的所有属性
    const teacherFields = this.teacherEntityRep.metadata.columns.map(col => col.propertyName);
    const userFields = this.userEntityRep.metadata.columns.map(col => col.propertyName);

    // 过滤出属于 TeacherEntity 和 UserEntity 的字段
    const teacherData = {} as TeacherEntity;
    const userData = {} as UserEntity;

    Object.keys(updateTeacherDto).forEach(key => {
      if (teacherFields.includes(key)) {
        teacherData[key] = updateTeacherDto[key];
      } else if (userFields.includes(key)) {
        userData[key] = updateTeacherDto[key];
      }
    });
    teacherData.teacherName = userData.nickName

    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.startTransaction();

    try {
      // 更新教师信息
      await queryRunner.manager.update(TeacherEntity, { id: updateTeacherDto.id }, teacherData);

      // 更新用户信息
      await queryRunner.manager.update(UserEntity, { userId: updateTeacherDto.userId }, userData);

      // 提交事务
      await queryRunner.commitTransaction();
      return ResultData.ok();
    } catch (error) {
      // 回滚事务
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      // 释放 QueryRunner 资源
      await queryRunner.release();
    }
  }


  /**
   * 根据教师ID删除教师，并同步删除关联的用户
   */
  async removeByTeacherId(teacherId: number, queryRunner?: QueryRunner): Promise<void> {
    const manager = queryRunner?.manager || this.dataSource.manager;

    // 查询教师是否存在
    const teacher = await manager.findOne(TeacherEntity, {
      where: { teacherId },
      select: ['teacherId'],
    });

    if (!teacher) return;

    // 软删教师
    await manager.update(TeacherEntity, { teacherId }, { delFlag: '1' });

    // 软删用户（可选）
    if (teacher.teacherId) {
      await manager.update(UserEntity, { userId: +teacher.teacherId }, { delFlag: '1' });
    }
  }

  /**
   * 批量删除教师并同步删除关联用户
   */
  async remove(teacherIds: number[]): Promise<any> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.startTransaction();

    try {
      for (const id of teacherIds) {
        await this.removeByTeacherId(id, queryRunner);
      }

      await queryRunner.commitTransaction(); // 提交事务
      return ResultData.ok();
    } catch (error) {
      await queryRunner.rollbackTransaction(); // 回滚事务
      throw error;
    } finally {
      await queryRunner.release(); // 释放资源
    }
  }

  /**
   * 供 UserService 调用的接口：根据 userId 删除教师数据
   */
  async removeByUserId(userId: number, queryRunner: QueryRunner): Promise<void> {
    const teacher = await queryRunner.manager.findOne(TeacherEntity, {
      where: { teacherId: userId },
      select: ['teacherId'],
    });

    if (teacher) {
      await queryRunner.manager.update(
          TeacherEntity,
          { teacherId: teacher.teacherId },
          { delFlag: '1' }
      );
    }
  }
}
